package com.wuseguang.springcloud.dao.jdbc;

import com.alibaba.fastjson.JSON;
import com.wuseguang.springcloud.JdbcTemplate.BaseTemplate;
import com.wuseguang.springcloud.entity.StudentAchievement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class StudentAchievementJdbc extends BaseTemplate {

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    public int batchAddSchoolAchievement(String schoolId, String terId, String list, String name, String teacherId, Integer type) {
        int a = 1;
        try {
            List<Map<String, Object>> parse = (List<Map<String, Object>>) JSON.parse(list);
            String sql = "insert into `school_achievement` (`class_id`, `classname`, `school_id`, `term_id`, `teacher_id`, `achievement_name`,`param`,`opertime`,`type`) values(?,?,?,?,?,?,?,now(),?)";
            String sql1 = "insert into `school_achievement_course` (`achievement_id`, `course_id`,`course_name`) values(?,?,?)";
            if (parse != null) {
                logger.info("batchAddSchoolAchievement,JSON==> parse={}", parse.toString());
                for (int j = 0; j < parse.size(); j++) {
                    Map<String, Object> map = parse.get(j);
                    Object classid = map.get("classid");
                    Object classname = map.get("classname");
                    Object param = map.get("param");
                    List<Map<String, Object>> list1 = (List<Map<String, Object>>) map.get("list");
                    Long aLong = updateByParameterGetId(sql, classid, classname, schoolId, terId, teacherId, name, param, type);
                    dao.batchUpdate(sql1, new BatchPreparedStatementSetter() {
                        @Override
                        public void setValues(PreparedStatement ps, int i) throws SQLException {
                            Map<String, Object> map1 = list1.get(i);
                            ps.setObject(1, aLong);
                            ps.setObject(2, map1.get("course_id"));
                            ps.setObject(3, map1.get("course_name"));
                        }

                        @Override
                        public int getBatchSize() {
                            return list1.size();
                        }
                    });
                }
            }
        } catch (Exception e) {
            a = -1;
            logger.info("批量添加异常,error={}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 手动回滚
        }
        return a;
    }


    public Map<String, Integer> studentList(String sql, Integer id) {

        return dao.query(sql, new Object[]{id}, rs -> {

            Map<String, Integer> map = new HashMap<String, Integer>();
            while (rs.next()) {
                map.put(rs.getString("student_name"), rs.getInt("id"));
            }
            return map;
        });
    }



    public int batchAdditionAchievement(String lists, Integer id) {
        int a = -1;
        try {

            List<Map<String, Object>> list = (List<Map<String, Object>>) JSON.parse(lists);
            String sql = "insert into `student_achievement` (`achievement_course_id`, `student_id`, `fraction`) values(?,?,?)";
            String sql1 = "DELETE FROM student_achievement WHERE  achievement_course_id IN (  SELECT id FROM  school_achievement_course WHERE achievement_id=? )";
            //String sql2 = "SELECT id,total_score FROM  school_achievement_course WHERE achievement_id=" + id;
            //Map<String, String> map2 = getMap(sql2, "id", "total_score");
            //logger.info("map2={}", map2.toString());
            if (list != null) {
                logger.info("batchAdditionAchievement,JSON==> list={},id={}", list.toString(), id);
                /*for (int i = 0; i < list.size(); i++) {
                    Map<String, Object> map = list.get(i);
                    if (Integer.parseInt(map2.get(map.get("achievement_course_id").toString())) < Integer.parseInt(map.get("score").toString())) {
                        return -1;
                    }
                }*/
                updateByParameterGetId(sql1, id);
                String listSql = "SELECT student_name ,id   FROM student WHERE class_id IN (SELECT class_id FROM  school_achievement WHERE  id=?)";

                Map<String, Integer> stringIntegerMap = studentList(listSql, id);

                dao.batchUpdate(sql, new BatchPreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement ps, int i) throws SQLException {
                        Map<String, Object> map = list.get(i);
                        ps.setObject(1, map.get("achievement_course_id"));
                        Integer nameId = stringIntegerMap.get(map.get("name").toString());
                        if (nameId == null) {
                            throw new RuntimeException("名字不存在");
                        }
                        ps.setObject(2, nameId);
                        ps.setObject(3, map.get("score"));
                    }

                    @Override
                    public int getBatchSize() {
                        return list.size();
                    }
                });
            }
            a = 1;
        } catch (Exception e) {
            a = -1;
            logger.info("批量添加异常,error={}", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 手动回滚
        }
        return a;
    }

}
